package com.hmall.order.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmall.common.dto.Address;
import com.hmall.common.dto.Item;
import com.hmall.feign.ItemFeign;
import com.hmall.feign.UserFeign;
import com.hmall.order.Interceptor.UserThreadLocal;
import com.hmall.order.mapper.OrderDetailMapper;
import com.hmall.order.mapper.OrderLogisticsMapper;
import com.hmall.order.mapper.OrderMapper;
import com.hmall.order.pojo.Order;
import com.hmall.order.pojo.OrderDetail;
import com.hmall.order.pojo.OrderLogistics;
import com.hmall.order.pojo.OrderParams;
import com.hmall.order.service.IOrderService;

import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class OrderService extends ServiceImpl<OrderMapper, Order> implements IOrderService {
    @Autowired
    ItemFeign itemFeign;
    @Autowired
    OrderMapper orderMapper;
    @Autowired
    OrderDetailMapper orderDetailMapper;
    @Autowired
    UserFeign userFeign;
    @Autowired
    OrderLogisticsMapper orderLogisticsMapper;
    @Override
    @GlobalTransactional
    public Long order(OrderParams orderParams) {
        Item item = itemFeign.getById(orderParams.getItemId());
        //新增订单
        Order order=new Order();
        order.setTotalFee((item.getPrice())*(orderParams.getNum()));
        order.setPaymentType(orderParams.getPaymentType());
        order.setStatus(1);
        order.setUserId(UserThreadLocal.get());
        order.setCreateTime(new Date());
        orderMapper.insert(order);
        //新增订单详情
        OrderDetail orderDetail=new OrderDetail();
        orderDetail.setOrderId(order.getId());
        BeanUtils.copyProperties(item,orderDetail);
        orderDetail.setNum(orderParams.getNum());
        orderDetail.setItemId(item.getId());
        orderDetail.setCreateTime(new Date());
        orderDetail.setUpdateTime(new Date());
        orderDetailMapper.insert(orderDetail);
        //新增订单地址表
        Address address = userFeign.findAddressById(orderParams.getAddressId());
        OrderLogistics orderLogistics=new OrderLogistics();
        BeanUtils.copyProperties(address,orderLogistics);
        orderLogistics.setCreateTime(new Date());
        orderLogistics.setUpdateTime(new Date());
        orderLogistics.setOrderId(order.getId());
        orderLogisticsMapper.insert(orderLogistics);
        //删减库存
        itemFeign.updateStock(orderParams.getItemId(),orderParams.getNum());
        return  order.getId();
    }
}
